import time
from selenium import webdriver
from selenium.webdriver.common.by import By

def read_sentences(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    cleaned_lines = [line.strip() for line in lines if line.strip()]
    return cleaned_lines

def save_to_file(data, output_file):
    with open(output_file, 'a', encoding='utf-8') as f:
        for entry in data:
            f.write(f"Heading: {entry['heading']}\n")
            f.write(f"Content: {entry['content']}\n\n")

def simple_selenium_demo():
    driver = webdriver.Chrome()

    try:
        driver.get("http://127.0.0.1:5001/")
        time.sleep(5)

        # 点击第三个元素
        elements = driver.find_elements(By.CLASS_NAME, "welcome-theme-option")
        if len(elements) >= 3:
            elements[2].click()
            print("已成功点击第三个元素")
        else:
            print("元素数量不足，未找到第三个元素")

        # 点击关闭按钮
        buttons = driver.find_elements(By.TAG_NAME, "button")
        for button in buttons:
            if "close_welcome_panel(true)" in button.get_attribute("onclick"):
                button.click()
                print("已成功点击关闭按钮")
                break
        else:
            print("未找到绑定 close_welcome_panel(true) 的按钮")

        time.sleep(5)

        # 读取输入文本
        filename = "question.txt"
        sentences = read_sentences(filename)
        num = 0

        # 发送问题
        for idx, sentence in enumerate(sentences, start=1):
            time.sleep(5)
            textarea = driver.find_element(By.CLASS_NAME, 'corpo_chat_inner.mainnav')
            textarea.send_keys(sentence)
            send_btn = driver.find_element(By.CSS_SELECTOR, '.corpo_chat_send_btn.mainnav')
            send_btn.click()
            time.sleep(5)
            num += 1
            if num == 5:
                break

        # 提取对话内容
        corpostyle_items = driver.find_elements(By.CLASS_NAME, 'corpostyleitem')
        results = []  # 保存所有结果

        for item in corpostyle_items:
            try:
                heading = item.find_element(By.CLASS_NAME, 'corpostyleitemheading').text
                content = item.find_element(By.CLASS_NAME, 'corpostyleitemcontent').text
                results.append({'heading': heading, 'content': content})
            except Exception as e:
                print(f"Error: {e}")

        # 保存结果到文本文件
        output_file = "output.txt"
        save_to_file(results, output_file)
        print(f"已将结果保存到 {output_file}")

        time.sleep(10)

    finally:
        driver.quit()

if __name__ == "__main__":
    simple_selenium_demo()
